package com.training.java.redbox.struts.web;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.training.java.redbox.struts.domain.Customer;
import com.training.java.redbox.struts.domain.CustomerDAO;
import com.training.java.redbox.struts.domain.CustomerDaoJdbcImpl;
import com.training.java.redbox.struts.domain.CustomerService;
import com.training.java.redbox.struts.domain.DAOException;
import com.training.java.redbox.struts.domain.ServiceException;

public class SignupFormAction  extends Action{
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		System.out.println("i am inside signupform action");
		
		ServletContext servletContext = servlet.getServletContext();
		WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
		CustomerService service	= context.getBean(CustomerService.class);
		
		SignUpForm signupForm = (SignUpForm) form;
		//CustomerDAO customerDao = new CustomerDaoJdbcImpl();

		String firstName = signupForm.getFirstname();
		String lastName =  signupForm.getLastname();
		String address =  signupForm.getAddress();
		String city =  signupForm.getCity();
		String state =  signupForm.getState();
		String zipCode =  signupForm.getZipcode();
		String username =  signupForm.getUsername();
		String password =  signupForm.getPassword();

		Customer customer = new Customer(0, firstName, lastName);
		customer.setAddress(address);
		customer.setCity(city);
		customer.setState(state);
		customer.setZipCode(zipCode);
		customer.setUserName(username);
		customer.setPassword(password);

		try {
			service.addCustomer(customer);
			request.setAttribute("AckMessage", "Your Account has been created. You can login here now.");
			
		} catch (ServiceException e) {
			e.printStackTrace();
		}


		return  mapping.findForward("login");
	}

}
